<?php

namespace Auth;

use Entity\UserHistory;
use Service\UserManager;

class Auth
{

    protected $_em;

    function __construct(\Doctrine\ORM\EntityManager $em = null)
    {
        $this->_em = $em;
    }

    function login($login, $password)
    {
        $user = $this->_em->getRepository("\Entity\User")->findOneBy(array('name' => $login, 'password' => $password));

        if ($user) {
            $_SESSION['auth'] = serialize($user);
            $user->setLastVisit(new \DateTime());
            
            // add history
            $user->addHistoryLogin($this->_getLoginHistory());

            $this->_em->flush();
            return true;
        }

        return false;
    }

    private function _getLoginHistory()
    {
        $history = new UserHistory();
        $ip = $this->_getRealIp();
        $history->setIp($ip);
        return $history;
    }

    private function _getRealIp()
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }

    function isAuth()
    {
        return isset($_SESSION['auth']);
    }

    /**
     * @return \Entity\User|null
     */
    public function getUser()
    {
        $manager = new UserManager($this->_em);
        return $manager->getUser();
    }

    function logout()
    {
        unset($_SESSION['auth']);
    }

}